namespace Pna.Framework
{
    using Appccelerate.Bootstrapper;
    using Appccelerate.Bootstrapper.Behavior;
    using Appccelerate.Bootstrapper.Configuration;
    using Appccelerate.Bootstrapper.Syntax;

    using Castle.Windsor;

    /// <summary>
    /// The PNA strategy.
    /// </summary>
    public class PnaStrategy : AbstractStrategy<IPnaExtension>
    {
        private readonly IWindsorContainer container;

        /// <summary>
        /// Initializes a new instance of the <see cref="PnaStrategy" /> class.
        /// </summary>
        /// <param name="container">The IOC container.</param>
        public PnaStrategy(IWindsorContainer container)
        {
            this.container = container;
        }

        protected override void DefineRunSyntax(ISyntaxBuilder<IPnaExtension> builder)
        {
            builder
                .Begin
                    .With(new ConfigurationSectionBehavior())
                    .With(new ExtensionConfigurationSectionBehavior())
                .Execute(extension => extension.BeforeStart())
                .Execute(() => this.container, (extension, mods) => extension.ContainerInitializing(mods))
                .Execute(() => this.container, (extension, ctx) => extension.ContainerInitialized(ctx))
                .Execute(extension => extension.Start());
        }

        protected override void DefineShutdownSyntax(ISyntaxBuilder<IPnaExtension> builder)
        {
            builder
                .Execute(extension => extension.BeforeStop())
                .Execute(extension => extension.Stop())
                .Execute(extension => extension.AfterStop())
                .End.With(new DisposeExtensionBehavior());
        }

        protected override void Dispose(bool disposing)
        {
            // Dispose the container
            this.container.Dispose();
            base.Dispose(disposing);
        }
    }
}